package com.mao.crowd.filter;

import com.mao.crowd.constant.AccessPassResources;
import com.mao.crowd.constant.CrowdConstant;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author: Administrator
 * @description:
 * @cteate 2021-06-22-16:01
 */
public class CrowdAccessFilter extends ZuulFilter {

    @Override
    public String filterType() {
        // pre指在目标微服务之前执行过滤
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 获取request对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        // 获取servletpath
        String servletPath = request.getServletPath();
        boolean result = AccessPassResources.PASS_RES_SET.contains(servletPath);
        if (result){
            return false;
        }

        // 如果是静态资源之类的,就返回false直接放行,所以这一层判断是相反的
        boolean staticResult = AccessPassResources.judgeCurrentPathwetherStaticResource(servletPath);
        if (staticResult){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 获取request对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        // 获取当前的session对象
        HttpSession session = request.getSession();

        // 从session中获取到已经登录的用户
        Object loginMember = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);

        // 判断loginMember是否为空
        if (loginMember == null){
            // 获取response对象
            HttpServletResponse response = currentContext.getResponse();

            session.setAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_ACCESS_FORBIDDEN);

            try {
                response.sendRedirect("/auth/member/to/login/page.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
